import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:silver_flutter/api.dart' as api;
import 'package:silver_flutter/event/user_events.dart';
import 'package:silver_flutter/login_page.dart';
import 'package:silver_flutter/event_bus.dart';

class Authed extends StatefulWidget {
  final WidgetBuilder builder;

  Authed({Key key, this.builder}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _AuthedState();
  }
}

class _AuthedState extends State<Authed> {
  StreamSubscription _loginSub;
  StreamSubscription _logoutSub;

  bool _isLoggedIn = api.isLoggedIn();

  @override
  void dispose() {
    _loginSub.cancel();
    _logoutSub.cancel();

    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _loginSub = eventBus.on(UserLoggedInEvent).listen((event) {
      setState(() {
        _isLoggedIn = true;
      });
    });

    _logoutSub = eventBus.on(UserLoggedOutEvent).listen((event) {
      setState(() {
        _isLoggedIn = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoggedIn) {
      return widget.builder(context);
    } else {
      return new Center(
        child: new FlatButton(
          onPressed: () {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (context) => new LoginPage(),
              ),
            );
          },
          child: new Text('大人，点击登录'),
        ),
      );
    }
  }
}
